﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Facebook;
using System.Text;

namespace NutriLeaf.Phone
{
    public partial class MainPage : PhoneApplicationPage
    {

        #region FacebookProperties
        //Facebook Constants
        string AppID = Constants.Facebook.AppID;
        private readonly string[] extendedPermissions = new[] { "user_about_me", "user_activities", "user_location", "user_likes", "user_interests", "friends_activities", "friends_about_me", "read_stream", "read_friendlists", "email", "user_birthday", "publish_stream", "offline_access" }; //permissions from facebook
        private bool LoggedIn = false;
        #endregion

        Settings.Settings Setting;
        bool registered;


        // Constructor
        public MainPage()
        {
            InitializeComponent();
            Setting = new Settings.Settings();
            Active = true;
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (Active)
            {
                if (!String.IsNullOrEmpty(Setting.FacebookAccessToken))
                {
                    if (Setting.User != null)
                    {
                        //move to Sync
                        Active = false;
                        NavigationService.Navigate(new Uri(Constants.Navigation.Sync, UriKind.RelativeOrAbsolute));
                        return;
                    }
                    else
                    {
                        //move to profile page
                        Active = false;
                        NavigationService.Navigate(new Uri(Constants.Navigation.Profile, UriKind.RelativeOrAbsolute));
                        return;
                    }
                }
            }
            
        }

        private void FacebookAuthenticationBrowser_Loaded(object sender, RoutedEventArgs e)
        {
            if (Active)
            {
                //when the browser page is loaded
                if (!LoggedIn)
                {
                    LoginToFacebook();
                }
            }

        }

        private Uri GetFacebookLoginURL()
        {

             FacebookOAuthClient oauth = new FacebookOAuthClient { AppId = AppID };
             Dictionary<string, object> parameters = new Dictionary<string, object>
                     {

                        { "response_type", "token" },

                         { "display", "touch" }

                     };

              if (extendedPermissions != null && extendedPermissions.Length > 0)
              {

                 StringBuilder scope = new StringBuilder();

                 scope.Append(string.Join(",", extendedPermissions));

                 parameters["scope"] = scope.ToString();

              }

             return oauth.GetLoginUrl(parameters);

         }

        private void LoginToFacebook()
         {
             FacebookAuthenticationBrowser.Navigate(GetFacebookLoginURL());
         }

        private void FacebookAuthenticationBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
             


             FacebookOAuthResult result;
             if (FacebookOAuthResult.TryParse(e.Uri, out result))
             {
                 if (result.IsSuccess)
                 {
                     HideBroswer();
                     LoggedIn = true;
                     Setting = new Settings.Settings();
                     Setting.FacebookAccessToken = result.AccessToken;
                     Setting.FacebookAccessTokenExpires = result.Expires;

                     //connect to service
                     AccountService.AccountServiceClient accountService = new AccountService.AccountServiceClient();
                     accountService.LogInCompleted += new EventHandler<AccountService.LogInCompletedEventArgs>(accountService_LogInCompleted);
                     accountService.LogInAsync(result.AccessToken, result.Expires);
                     
                 }
                 else
                 {
                     MessageBox.Show(result.ErrorDescription + " \n" + result.ErrorReason);
                 }
            }
        }

        private void HideBroswer()
        {
            FacebookAuthenticationBrowser.Visibility = System.Windows.Visibility.Collapsed; //hide the browser
        }

        private void ShowBrowser()
        {
            FacebookAuthenticationBrowser.Visibility = System.Windows.Visibility.Visible; //show the browser
        }
        
        void accountService_LogInCompleted(object sender, AccountService.LogInCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                if (e.Result == AccountService.LoginStatus.Registered)
                {
                    registered = true;
                }
            }
            else
            {
                return;
            }
            AccountService.AccountServiceClient client = new AccountService.AccountServiceClient();
            client.GetUserDataCompleted += new EventHandler<AccountService.GetUserDataCompletedEventArgs>(client_GetUserDataCompleted);
            client.GetUserDataAsync(Setting.FacebookAccessToken.ToString());
        }

        void client_GetUserDataCompleted(object sender, AccountService.GetUserDataCompletedEventArgs e)
        {
            if (Active)
            {
                if (e.Error == null)
                {
                    Setting.User = e.Result.user;
                    Setting.UserProfile = e.Result.profile;
                    if (registered)
                    {
                        //go to profile page
                        Active = false;
                        NavigationService.Navigate(new Uri(Constants.Navigation.Profile + "?Registered=true", UriKind.RelativeOrAbsolute));
                    }
                    else
                    {
                        //go to Sync
                        Active = false;
                        NavigationService.Navigate(new Uri(Constants.Navigation.Sync, UriKind.RelativeOrAbsolute));
                    }
                }
                else
                {
                    MessageBox.Show("We're sorry, we could not communicate with the service at the server end.Please Try again.");
                }
            }
        }





        public bool Active { get; set; }
    }
}